﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraNavBar;
using WindowsForms.Class;
using DevExpress.XtraBars.Ribbon.ViewInfo;
using WindowsForms.service;
using Model;



namespace WindowsForms
{
    public partial class SalesManagement : DevExpress.XtraEditors.XtraForm
    {
        private const string SPACE = "      ";

        NavBarGroup lastSelectedGroup;
        GridHitInfo hitInfoGrid = null;
        RibbonHitInfo dragItemHitInfo = null;
        ConvertToList convert = new ConvertToList();

        Service1 iQuery;

        private Tables tableSelected;
        Menus menuSelected;
        Bookings booking;
        private int totalMoney = 0;

        List<Tables> lsTable = null;
        List<Menus> lsMenu;
        List<Regions> lsRegion;
        List<TableModel> lsTableModel;
        List<BookingDetails> bookingDetailList;
        List<BookingDetailModel> bookingDetailModelList;

        List<BookingDetailModel> bookingDetailModelAddMenuList;


        public SalesManagement()
        {
            iQuery = new Service1();
            InitializeComponent();
            mainGallery.AllowDrop = true;

            GetAllRegion();
            GetTables();
            BuildTableModel();
            GetMenus();

            InitNavBar(false);
            UpdateMainGalleryContent(true);

            btnEditAfterProcessingRequest.Enabled = false;
            btnPrintBill.Enabled = false;
        }

        private void GetAllRegion()
        {
            lsRegion = convert.ConvertTolistRegions(iQuery.SelectRegionsAll().Tables[0]);
        }

        private void GetTables()
        {
            lsTable = convert.ConvertTolistTables(iQuery.SelectTablesAll().Tables[0]);
        }

        private void BuildTableModel()
        {
            lsTableModel = new List<TableModel>();
            foreach (Regions re in lsRegion)
            {
                TableModel tableModel = new TableModel();
                tableModel.Region.RegionID = re.RegionID;
                tableModel.Region.RegionName = re.RegionName;
                foreach (Tables t in lsTable)
                {
                    if (re.RegionID == t.RegionID)
                    {
                        tableModel.TableList.Add(t);
                    }
                }
                lsTableModel.Add(tableModel);
            }
        }

        private void InitNavBar(bool onlyRegion)
        {
            navBarControl1.SelectedLink = null;
            foreach (NavBarGroup group in navBarControl1.Groups)
            {
                if (onlyRegion && group != tableGroup)
                {
                    continue;
                }
                for (int i = group.ItemLinks.Count - 1; i >= 0; i--)
                {
                    navBarControl1.Items.Remove(group.ItemLinks[i].Item);
                }
            }
            navBarControl1.BeginUpdate();
            try
            {
                foreach (TableModel region in lsTableModel)
                {
                    NavBarItem item = CreateRegionItem(region);
                    navBarControl1.Items.Add(item);
                    tableGroup.ItemLinks.Add(item);
                }
                if (onlyRegion)
                {
                    return;
                }
            }
            finally { navBarControl1.EndUpdate(); }
            if (navBarControl1.Items.Count > 0)
            {
                navBarControl1.SelectedLink = navBarControl1.Items[0].Links[0];
            }

        }
        private NavBarItem CreateRegionItem(TableModel region)
        {
            NavBarItem item = new NavBarItem();
            item.Caption = region.Region.RegionName;
            item.Hint = region.Region.RegionName;
            item.Tag = region;
            item.LinkClicked += new NavBarLinkEventHandler(OnRegionLinkClicked);
            return item;
        }

        private void OnRegionLinkClicked(object sender, NavBarLinkEventArgs e) { }

        private void ClearGalleryAndImages()
        {
            mainGallery.Gallery.Groups.Clear();
            foreach (GalleryItemGroup group in mainGallery.Gallery.Groups)
            {
                if (group.CaptionControl != null)
                {
                    group.CaptionControl.Dispose();
                    group.CaptionControl = null;
                    foreach (GalleryItem item in group.Items)
                    {
                        if (item.Image != null)
                        {
                            item.Image.Dispose();
                            item.Image = null;
                        }
                    }
                }
            }
        }

        private GalleryItemGroup CreateRegionGroup(TableModel tableModel)
        {
            GalleryItemGroup group = new GalleryItemGroup();
            group.Tag = tableModel;
            group.Caption = tableModel.Region.RegionName;
            group.CaptionAlignment = GalleryItemGroupCaptionAlignment.Stretch;
            return group;
        }

        private GalleryItem CreatePhotoGalleryItem(Tables tb)
        {
            GalleryItem item = new GalleryItem();
            item.Caption = tb.TableName;
            item.Hint = tb.TableName;
            if (!tb.IsBlank)
            {
                item.Image = global::WindowsForms.Properties.Resources.Restaurant1;
            }
            else
            {
                item.Image = global::WindowsForms.Properties.Resources.Restaurant2;
            }
            item.Tag = tb;
            return item;
        }

        private void ProcessRegion(TableModel tableModel, bool showEditButtons)
        {
            GalleryItemGroup group = CreateRegionGroup(tableModel);

            mainGallery.Gallery.Groups.Add(group);
            foreach (Tables tb in tableModel.TableList)
            {
                group.Items.Add(CreatePhotoGalleryItem(tb));
            }
        }

        private void ProcessRegion(TableModel tableModel)
        {
            ProcessRegion(tableModel, true);
        }

        private void ProcessRegions()
        {
            mainGallery.Gallery.BeginUpdate();
            try
            {
                ClearGalleryAndImages();
                foreach (TableModel Region in lsTableModel)
                {
                    ProcessRegion(Region);
                }
            }
            finally
            {
                mainGallery.Gallery.EndUpdate();
            }
        }

        private GalleryItemGroup GetGalleryGroupByTag(object tag)
        {
            foreach (GalleryItemGroup group in mainGallery.Gallery.Groups)
            {
                if (group.Tag == tag)
                {
                    return group;
                }
            }
            return null;
        }

        private void ScrollToRegion(TableModel tableModel, bool bAnimated)
        {
            mainGallery.Gallery.ScrollTo(GetGalleryGroupByTag(tableModel), bAnimated);
        }

        private void UpdateMainGalleryContent(bool forceProcess)
        {
            if (navBarControl1.SelectedLink == null)
            {
                ClearGalleryAndImages();
                return;
            }
            TableModel tableModel = navBarControl1.SelectedLink.Item.Tag as TableModel;

            bool shouldRecreateGallery = lastSelectedGroup != navBarControl1.SelectedLink.Group || forceProcess;

            if (tableModel != null)
            {
                if (shouldRecreateGallery)
                    ProcessRegions();
                ScrollToRegion(tableModel, !shouldRecreateGallery);
            }
            //else if (path != null)
            //{
            //    if (shouldRecreateGallery)
            //    {
            //        if (isOtherFiles)
            //            ProcessOthers();
            //        else
            //            ProcessFolders();
            //    }
            //    if (isOtherFiles)
            //        ScrollToFile(path.Path, !shouldRecreateGallery);
            //    else
            //        ScrollToFolder(path, !shouldRecreateGallery);
            //}
            //UpdateItemsEnabledState();
        }


        private void navBarControl1_SelectedLinkChanged(object sender, DevExpress.XtraNavBar.ViewInfo.NavBarSelectedLinkChangedEventArgs e)
        {
            UpdateMainGalleryContent(false);
            lastSelectedGroup = e.Group;
        }

        private void galleryControlGallery1_ItemCheckedChanged(object sender, GalleryItemEventArgs e)
        {
            tableSelected = (Tables)e.Item.Tag;

            if (tableSelected != null)
            {
                MenuCalled(tableSelected);
            }
        }

        private void MenuCalled(Tables tbSelected)
        {
            groupControl2.Visible = true;
            groupControl2.Text = "Thực đơn đã gọi ở bàn: " + tbSelected.TableName;

            if (tbSelected.IsBlank) // ban da goi mon
            {
                //btnRemoveMenu.Enabled = false;

                btnEditAfterProcessingRequest.Enabled = true;
                btnPrintBill.Enabled = true;
                //To do
                List<Bookings> lstb = new List<Bookings>();
                DataTable dt = new DataTable();
                dt = iQuery.SelectBookingByTableID(tbSelected.TableID).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    lstb = convert.ConvertTolistBooking(dt);
                    booking = lstb[lstb.Count-1];
                    bookingDetailList = convert.ConvertTolistBookingDetails(iQuery.SelectBookingDetailsByBookingID(booking.BookingID).Tables[0]);
                    //booking = iQuery.Bk_GetBookingByID(tbSelected.TableID);
                    //bookingDetailList = iQuery.Bkd_GetBookingDetailByID(booking.BookingID);
                    bookingDetailModelList = new List<BookingDetailModel>();
                    if (bookingDetailList.Count > 0)
                    {
                        bookingDetailList.ForEach(delegate(BookingDetails bkd)
                        {
                            BookingDetailModel bookDetailModel = new BookingDetailModel();
                            bookDetailModel.BookingDetailID = bkd.BookingDetailID;
                            bookDetailModel.BookingID = bkd.BookingID;
                            bookDetailModel.MenuID = bkd.MenuID;
                            bookDetailModel.MenuName = bkd.MenuName;
                            bookDetailModel.Price = bkd.Price;
                            bookDetailModel.Quantity = bkd.Quantity;
                            bookDetailModel.Status = string.Empty;
                            bookDetailModel.UnitName = bkd.UnitName;
                            bookDetailModel.Money = bkd.Price * bkd.Quantity;
                            bookingDetailModelList.Add(bookDetailModel);
                        });
                    }
                }
                //Sort asc by menuName
                //bookingdetailmodellist.sort(delegate(bookingdetailmodel o1, bookingdetailmodel o2)
                //{
                //    return o1.menuname.compareto(o2.menuname);
                //});

                totalMoney = bookingDetailModelList.Sum(x => x.Money);
                txtTotalMoney.Text = totalMoney.ToString();
                gridControl2.DataSource = bookingDetailModelList;
                gridControl2.Refresh();
            }
            else // ban trong
            {
                btnRemoveMenu.Enabled = true;
                btnEditAfterProcessingRequest.Enabled = false;
                btnPrintBill.Enabled = false;

                txtTotalMoney.Text = "0";
                bookingDetailModelList = new List<BookingDetailModel>();
                gridControl2.DataSource = bookingDetailModelList;
                gridControl2.Refresh();
            }
        }

        //GOI MON
        private void GetMenus()
        {
            
            lsMenu = convert.ConvertTolistMenus(iQuery.SelectMenusAll().Tables[0]);
            gridControl1.ShowOnlyPredefinedDetails = true;
            gridControl1.DataSource = lsMenu;
            bookingDetailList = new List<BookingDetails>();
            bookingDetailModelList = new List<BookingDetailModel>();
        }

        private string DataRow(DataRow dr)
        {
            string s = string.Empty;
            if (dr != null)
                foreach (object o in dr.ItemArray)
                {
                    s = (s == string.Empty ? string.Empty : s + "; ") + o.ToString();
                }
            return s;
        }

        private void gridControl1_MouseDown(object sender, MouseEventArgs e)
        {
            hitInfoGrid = gridView1.CalcHitInfo(new Point(e.X, e.Y));
        }

        private void gridControl1_MouseMove(object sender, MouseEventArgs e)
        {
            if (hitInfoGrid == null) return;
            if (e.Button != MouseButtons.Left) return;
            Rectangle dragRect = new Rectangle(new Point(
                hitInfoGrid.HitPoint.X - SystemInformation.DragSize.Width / 2,
                hitInfoGrid.HitPoint.Y - SystemInformation.DragSize.Height / 2), SystemInformation.DragSize);
            if (!dragRect.Contains(new Point(e.X, e.Y)))
            {
                if (hitInfoGrid.InRowCell)
                    gridControl1.DoDragDrop((gridView1.GetRowCellDisplayText(hitInfoGrid.RowHandle, hitInfoGrid.Column)), DragDropEffects.Copy);
                if (hitInfoGrid.HitTest == GridHitTest.RowIndicator)
                {
                    string data = DataRow(gridView1.GetDataRow(hitInfoGrid.RowHandle));
                    gridControl1.DoDragDrop(data, DragDropEffects.Copy);
                }
            }

            int[] rows = gridView1.GetSelectedRows();
            menuSelected = gridView1.GetRow(rows[rows.Length - 1]) as Menus;
        }

        private void gridControl2_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        private void gridControl2_DragDrop(object sender, DragEventArgs e)
        {
            if (this.hitInfoGrid != null)
            {
                SelectedMenus();
            }
        }


        private void SelectedMenus()
        {
            if (tableSelected != null)
            {
                int[] rows = gridView1.GetSelectedRows();
                menuSelected = gridView1.GetRow(rows[rows.Length - 1]) as Menus;
                if (menuSelected != null)
                {
                    BookingDetailModel bookingDetail = bookingDetailModelList.Find(delegate(BookingDetailModel bkd) { return bkd.MenuID == menuSelected.MenuID; });
                    if (bookingDetail == null)
                    {
                        bookingDetailModelList.Add(new BookingDetailModel
                        {
                            MenuID = menuSelected.MenuID,
                            Price = menuSelected.Price,
                            Quantity = 1,
                            Status = string.Empty,
                            MenuName = menuSelected.MenuName,
                            UnitName = menuSelected.UnitName,
                            Money = menuSelected.Price
                        });
                    }
                    else
                    {
                        int index = bookingDetailModelList.FindIndex(x => x.MenuID == menuSelected.MenuID);
                        bookingDetailModelList[index].Quantity++;
                        bookingDetailModelList[index].Money = bookingDetailModelList[index].Quantity * menuSelected.Price;
                    }
                    txtTotalMoney.Text = bookingDetailModelList.Sum(x => x.Money).ToString();
                    gridControl2.DataSource = bookingDetailModelList;
                    gridView2.RefreshData();
                }
                else
                {
                    MessageBox.Show("Bạn chưa chọn món", "Chọn món", MessageBoxButtons.OK);
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa chọn bàn", "Chọn bàn", MessageBoxButtons.OK);
            }
        }

        private void btnSelectMenu_Click(object sender, EventArgs e)
        {
            SelectedMenus();
        }

        private void btnRemoveMenu_Click(object sender, EventArgs e)
        {
            if (bookingDetailModelList != null && bookingDetailModelList.Count > 0)
            {
                int[] rows = gridView2.GetSelectedRows();
                BookingDetailModel bookingDetailModel = gridView2.GetRow(rows[rows.Length - 1]) as BookingDetailModel;
                {
                    int index = bookingDetailModelList.FindIndex(x => x.MenuID == bookingDetailModel.MenuID);
                    if (bookingDetailModelList[index].Quantity > 0)
                    {
                        bookingDetailModelList[index].Quantity--;
                        bookingDetailModelList[index].Money = bookingDetailModelList[index].Quantity * bookingDetailModel.Price;
                    }
                }
                txtTotalMoney.Text = bookingDetailModelList.Sum(x => x.Money).ToString();
                gridControl2.DataSource = bookingDetailModelList;
                gridView2.RefreshData();
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

        }


        private void mainGallery_MouseDown(object sender, MouseEventArgs e)
        {
            this.hitInfoGrid = null;
            GalleryControl galControl = (GalleryControl)sender;
            RibbonHitInfo hitInfo = galControl.CalcHitInfo(e.Location);
            if (hitInfo.InGalleryItem)
            {
                dragItemHitInfo = hitInfo;
                tableSelected = dragItemHitInfo.GalleryItem.Tag as Tables;
                return;
            }

            dragItemHitInfo = null;
        }

        private void mainGallery_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || Control.ModifierKeys != Keys.None || dragItemHitInfo == null)
                return;

            Size dragSize = SystemInformation.DragSize;
            Rectangle dragRect = new Rectangle(dragItemHitInfo.HitPoint.X - dragSize.Width / 2, dragItemHitInfo.HitPoint.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height);
            if (!(dragRect.Contains(e.Location)))
            {
                mainGallery.DoDragDrop(dragItemHitInfo.GalleryItem, DragDropEffects.Copy);
            }
        }

        private void mainGallery_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(GalleryItem)))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void mainGallery_DragDrop(object sender, DragEventArgs e)
        {
            if (!(e.Data.GetDataPresent(typeof(GalleryItem))))
                return;

            GalleryItem draggedItem = e.Data.GetData(typeof(GalleryItem)) as GalleryItem;

            GalleryControl galControl = (GalleryControl)sender;
            RibbonHitInfo hitInfo = galControl.CalcHitInfo(galControl.PointToClient(new Point(e.X, e.Y)));
            Tables tableChangeDestination = null;
            if (hitInfo != null && hitInfo.GalleryItem != null)
            {
                tableChangeDestination = (Tables)hitInfo.GalleryItem.Tag;
            }

            if (!tableSelected.IsBlank)
            {
                MessageBox.Show("Bạn hãy chọn bàn đã gọi món", "Chọn bàn", MessageBoxButtons.OK);
            }
            else
            {
                if (tableChangeDestination != null && !tableChangeDestination.IsBlank)//Doi ban dang su dung sang ban trong
                {
                    string msConfirmChangeTable = string.Format("Bạn có muốn đổi từ {0} sang {1} không?", tableSelected.TableName, tableChangeDestination.TableName);
                    DialogResult dr = MessageBox.Show(msConfirmChangeTable, "Xác nhận", MessageBoxButtons.YesNo);
                    if (dr == System.Windows.Forms.DialogResult.Yes)
                    {
                        Bookings bk = convert.ConvertTolistBooking(iQuery.SelectBookingByTableID(tableSelected.TableID).Tables[0])[0];

                        //chuyen mon sang ban moi

                        bk.TableID = tableChangeDestination.TableID;
                        iQuery.UpdateBooking(bk.BookingID, bk.TableID, bk.StaffID, bk.BookingNumber, bk.BookingDate, bk.TotalAmount, bk.IsDeleted);
                        //iQuery.Bk_EditBooking(bk);
                        MessageBox.Show("Đã đổi bàn thành công", "Đổi bàn", MessageBoxButtons.OK);
                        //cap nhat ban da doi sang chua su dung
                        tableSelected.IsBlank = false;

                        iQuery.UpdateTable(tableSelected.TableID, tableSelected.TableName, tableSelected.RegionID, tableSelected.Description, tableSelected.IsBlank, tableSelected.IsDeleted);
                        //iQuery.Tab_EditTable(tableSelected);

                        //cap nhat trang thai ban sang [da su dung]

                        tableChangeDestination.IsBlank = true;
                        iQuery.UpdateTable(tableChangeDestination.TableID, tableChangeDestination.TableName, tableChangeDestination.RegionID, tableChangeDestination.Description
                            , tableChangeDestination.IsBlank, tableChangeDestination.IsDeleted);
                        //iQuery.Tab_EditTable(tableChangeDestination);
                        UpdateMainGalleryContent(true);
                        MenuCalled(tableChangeDestination);
                    }
                }
            }
        }

        private void btnProcessingRequest_Click(object sender, EventArgs e)
        {
            if (tableSelected != null)// da chon ban
            {
                bookingDetailList.Clear();
                bookingDetailModelAddMenuList = new List<BookingDetailModel>();
                bookingDetailModelList.ForEach(delegate(BookingDetailModel bookingModel)
                {
                    BookingDetails bookingDetail = new BookingDetails();
                    bookingDetail.BookingDetailID = bookingModel.BookingDetailID;
                    bookingDetail.BookingID = bookingModel.BookingID;
                    bookingDetail.MenuID = bookingModel.MenuID;
                    bookingDetail.Price = bookingModel.Price;
                    bookingDetail.Quantity = bookingModel.Quantity;
                    bookingDetail.Status = bookingModel.Status;
                    bookingDetailList.Add(bookingDetail);
                });

                if (!tableSelected.IsBlank) // ban trong
                {
                    if (bookingDetailList.Count > 0)
                    {
                        Bookings book = new Bookings();
                        book.TableID = tableSelected.TableID;
                        book.StaffID = Login.STAFF_IDENTITY.StaffID;
                        book.BookingDate = DateTime.Now;

                        //set bookingNumber
                        string prefixBillCode = DateTime.Now.ToString(Constants.PREFIX_BILL_CD);
                        //To do
                        string bookingNumber = null;
                        try
                        {
                            bookingNumber = iQuery.SelectMaxBookingNumberInDate();
                        }
                        catch { }
                        if (string.IsNullOrEmpty(bookingNumber))
                        {
                            book.BookingNumber = string.Concat(prefixBillCode, Constants.HYPHEN, Constants.FIST_CODE);
                        }
                        else
                        {
                            string strCode = bookingNumber.Replace(Constants.HYPHEN, string.Empty);
                            decimal decimalCode = Convert.ToDecimal(strCode);
                            decimalCode++;

                            string strBookingNum = Convert.ToString(decimalCode);
                            string bkNumber = string.Concat(strBookingNum.Substring(0, 6), Constants.HYPHEN, strBookingNum.Substring(6));

                            book.BookingNumber = bkNumber;
                        }
                        using (PrintAddMenu print = new PrintAddMenu())
                        {
                            print.BookingDetailModelLs = bookingDetailModelList;
                            print.Message = "Danh sách món yêu cầu chế biến cho " + tableSelected.TableName;
                            if (print.ShowDialog(this.FindForm()) == DialogResult.OK)
                            {
                                iQuery.InsertBooking(book.TableID, book.StaffID, book.BookingNumber, book.BookingDate, book.TotalAmount);
                                book.BookingID = int.Parse(iQuery.SelectMaxBookingId());
                                //iQuery.Bk_NewBooking(book);

                                bookingDetailList.ForEach(delegate(BookingDetails bkd)
                                {
                                    bkd.BookingID = book.BookingID;
                                });

                                //iQuery.Bkd_NewBookingDetail(bookingDetailList);
                                foreach(BookingDetails item in bookingDetailList)
                                {
                                    iQuery.InsertBookingDetail(item.BookingID, item.MenuID, item.Status, item.Price, item.Quantity);
                                }
                                
                                // CalculateMaterialProcess(bookingDetailModelList);
                                string ms = "Bạn đã gọi món thành công: " + tableSelected.TableName;
                                MessageBox.Show(ms, "Gọi món", MessageBoxButtons.OK);

                                //cap nhat trang thai ban sang [da su dung]
                                tableSelected.IsBlank = true;
                                //iQuery.Tab_EditTable(tableSelected);
                                iQuery.UpdateTable(tableSelected.TableID, tableSelected.TableName, tableSelected.RegionID, tableSelected.Description, tableSelected.IsBlank, tableSelected.IsDeleted);
                                ProcessRegions();
                                MenuCalled(tableSelected);
                            }
                        }
                    }
                }
                else
                {
                    using (PrintAddMenu print = new PrintAddMenu())
                    {
                        print.BookingDetailModelLs = bookingDetailModelList;
                        print.Message = "Danh sách món yêu cầu chế biến thêm cho " + tableSelected.TableName;
                        if (print.ShowDialog(this.FindForm()) == DialogResult.OK)
                        {
                            //goi them mon
                            List<BookingDetails> bookingDetailNew = bookingDetailList.FindAll(delegate(BookingDetails menu)
                            {
                                return menu.BookingDetailID == 0;
                            });

                            if (bookingDetailNew != null && bookingDetailNew.Count > 0)
                            {
                                bookingDetailNew.ForEach(delegate(BookingDetails bkd)
                                {
                                    bkd.BookingID = booking.BookingID;
                                });

                                foreach (BookingDetails item in bookingDetailNew)
                                {
                                    iQuery.InsertBookingDetail(item.BookingID, item.MenuID, item.Status, item.Price, item.Quantity);
                                }
                            }

                            //chinh sua goi mon
                            List<BookingDetails> bookingDetailEdit = bookingDetailList.FindAll(delegate(BookingDetails bookingdt)
                            {
                                return bookingdt.BookingDetailID != 0;
                            });
                            if (bookingDetailEdit != null && bookingDetailEdit.Count > 0)
                            {
                                //iQuery.Bkd_EditBookingDetail(bookingDetailEdit);
                                foreach (BookingDetails item in bookingDetailEdit)
                                {
                                    iQuery.UpdateBookingDetail(item.BookingDetailID,item.BookingID,item.MenuID,item.Status,item.Price,item.Quantity,item.IsDeleted);
                                }
                                string ms = "Bạn đã thay đổi món thành công: " + tableSelected.TableName;
                                MessageBox.Show(ms, "Gọi món", MessageBoxButtons.OK);
                                MenuCalled(tableSelected);
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Bạn hãy chọn bàn cần gọi món", "Chọn bàn", MessageBoxButtons.OK);
            }
        }

        private void btnEditAfterProcessingRequest_Click(object sender, EventArgs e)
        {
            using (EditAfterProcessingRequest print = new EditAfterProcessingRequest())
            {
                MenuCalled(tableSelected);
                print.BookingDetailModelLs = bookingDetailModelList.ToList();
                print.Message = "Danh sách món đã gọi ở " + tableSelected.TableName;

                if (print.ShowDialog(this.FindForm()) == DialogResult.OK)
                {
                    bookingDetailModelList.ForEach(delegate(BookingDetailModel bkDt)
                    {
                        print.BookingDetailModelLs.ForEach(delegate(BookingDetailModel bkDtEdit)
                        {
                            if (bkDt.MenuID == bkDtEdit.MenuID)
                            {
                                bkDt.Quantity = bkDtEdit.Quantity - bkDtEdit.QuantityReturn;
                            }
                        });
                    });

                    bookingDetailList.Clear();
                    bookingDetailModelList.ForEach(delegate(BookingDetailModel bookingModel)
                    {
                        BookingDetails bookingDetail = new BookingDetails();
                        bookingDetail.BookingDetailID = bookingModel.BookingDetailID;
                        bookingDetail.BookingID = bookingModel.BookingID;
                        bookingDetail.MenuID = bookingModel.MenuID;
                        bookingDetail.Price = bookingModel.Price;
                        bookingDetail.Quantity = bookingModel.Quantity;
                        bookingDetail.Status = bookingModel.Status;
                        bookingDetailList.Add(bookingDetail);
                    });

                    List<BookingDetailModel> bookingDetailModelLsUpdate = print.BookingDetailModelLs.FindAll(x => x.QuantityReturn > 0);
                    if (print.IsRestoreWH)
                    {
                       // iQuery.Bkd_EditBookingDetail(bookingDetailList);
                        foreach (BookingDetails item in bookingDetailList)
                        {
                            iQuery.UpdateBookingDetail(item.BookingDetailID, item.BookingID, item.MenuID, item.Status, item.Price, item.Quantity, item.IsDeleted);
                        }
                        //Cong vao KHO
                        //CalculateMaterialProcess(bookingDetailModelLsUpdate, false);
                        string ms = "Bạn đã thay đổi món thành công: " + tableSelected.TableName;
                        MessageBox.Show(ms, "Gọi món", MessageBoxButtons.OK);
                        MenuCalled(tableSelected);
                    }
                }
            }
        }

        private void btnPrintBill_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Bạn có muốn thanh toán không?", "Xác nhận", MessageBoxButtons.YesNo);
            if (dr == System.Windows.Forms.DialogResult.Yes)
            {
                //cap nhat trang thai ban sang [chua su dung]
                tableSelected.IsBlank = false;
                iQuery.UpdateTable(tableSelected.TableID, tableSelected.TableName, tableSelected.RegionID, tableSelected.Description, tableSelected.IsBlank, tableSelected.IsDeleted);

                //Tong so tien thanh toan
                booking.TotalAmount = totalMoney;
                iQuery.UpdateBooking(booking.BookingID, booking.TableID, booking.StaffID, booking.BookingNumber, booking.BookingDate, booking.TotalAmount, booking.IsDeleted);

                //insert to historyBookings form bookingdetail and delete bookingdetail
                iQuery.DeleteBookingDetail(booking.BookingID);

                gridControl2.DataSource = new List<BookingDetailModel>();
                gridControl2.Refresh();
                UpdateMainGalleryContent(true);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            mainGallery.AllowDrop = true;

            GetAllRegion();
            GetTables();
            BuildTableModel();
            GetMenus();

            InitNavBar(false);
            UpdateMainGalleryContent(true);

            btnEditAfterProcessingRequest.Enabled = false;
            btnPrintBill.Enabled = false;
            gridControl2.DataSource = null;
        }
    }
}